<?php

namespace App\Http\Controllers;
use App\Repositories\ConfigRepository;
use App\Traits\ResetPassword;
use Lcobucci\JWT\Parser;
use RuntimeException;

class HomeController extends Controller {
	use ResetPassword;

	protected $model, $publicKey;

	public function __construct(ConfigRepository $config) {
		$this->model = $config;
	}

	public function index() {
		list($showConfig, $seoConfig, $resumeConfig, $contactConfig) = $this->getCacheConfig();
		$resumeConfig['password'] = md5('dai-' . $resumeConfig['password'] . '-jin');
		return view('welcome', compact('showConfig', 'seoConfig', 'resumeConfig', 'contactConfig'));
	}

	public function hash($token) {
		$this->checkToken($token);
		list($showConfig, $seoConfig, $resumeConfig, $contactConfig) = $this->getCacheConfig();
		return view('hash', compact('showConfig', 'seoConfig', 'resumeConfig', 'contactConfig'));
	}

	private function getCacheConfig() {
		$show = $this->model->getShowConfig();
		$seo = $this->model->getSeoConfig();
		$resume = $this->model->getResumeConfig();
		$contact = $this->model->getContactMe();

		return [$show, $seo, $resume, $contact];
	}

	private function checkToken($jwt) {
		try {
			$token = (new Parser())->parse($jwt);
		} catch (RuntimeException $exception) {
			abort(404);
		}
		if ($token->getClaim('sub') != 1) {
			abort(404);
		}
	}
}
